package nl.tue.be.ds.duraark.bSDD;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.NewCookie;

import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.DeserializationConfig.Feature;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class ClientUtilities {
	public static NewCookie cookie;

	public static Client getClient(){
		ClientConfig clientConfig = new DefaultClientConfig();
		clientConfig.getClasses().add(JacksonJsonProvider.class);
		clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING,Boolean.TRUE);
		Client client = Client.create(clientConfig);
		return client;
	}

	public static void login() {
		WebResource webResource = getClient().resource("http://bsddpilot.catenda.no/api/4.0/session/login");
		MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
		formData.add("email", "demo");
		formData.add("password", "demo");

		webResource.accept(MediaType.APPLICATION_JSON_TYPE);
		webResource.type(MediaType.APPLICATION_FORM_URLENCODED);

		ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, formData);
		cookie = response.getCookies().get(0);
	}
	
/*	public static List<NewCookie> getCookies(Client client) {
		WebResource webResource = client.resource("http://bsddpilot.catenda.no/api/4.0/session/login");
		MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
		formData.add("email", "demo");
		formData.add("password", "demo");

		webResource.accept(MediaType.APPLICATION_JSON_TYPE);
		webResource.type(MediaType.APPLICATION_FORM_URLENCODED);

		ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, formData);
		return response.getCookies();
	}*/
	
	public static void logout(){
		getClient().resource("http://bsddpilot.catenda.no/api/4.0/session/logout");
	}
	
	
	public static ObjectMapper getMapper(){
		ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);
		mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.configure(Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
		return mapper;
	}
	
}
